//
//  EBookCell.swift
//  clreader
//
//  Created by colin on 2019/3/6.
//  Copyright © 2019 colin. All rights reserved.
//

import UIKit

extension HomeViewController {
    
    class EBookCell: UITableViewCell {
        
        var selectedHandle:((_ goods:JSONObject?)->Void)?

        static let reuseId = "EBookCell"
        
        static var cellHeight:CGFloat {
            let padding = UIEdgeInsets(top: 15.0, left: 15.0, bottom: 15.0, right: 15.0)
            let ratio:CGFloat = 125.0 / 90.0
            let distance:CGFloat = 35.0
            let columnCount:CGFloat = 3.0
            let imageWidth = (UIScreen.main.bounds.width - padding.left - padding.right - (columnCount - 1) * distance) / columnCount
            let imageHeight = imageWidth * ratio
            return imageHeight + padding.top + padding.bottom + 40.0
        }
        
        private var contentCollectionView:UICollectionView?
        
        private var datas:[JSONObject]?
        
        override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
            super.init(style: style, reuseIdentifier: reuseIdentifier)
            self.do {
                $0.selectionStyle = .none
                $0.backgroundColor = UIColor.clear
                $0.contentView.backgroundColor = UIColor.clear
            }
            
            let padding = UIEdgeInsets(top: 15.0, left: 15.0, bottom: 15.0, right: 15.0)
            let distance:CGFloat = 35.0
            let columnCount:CGFloat = 3.0
            let imageWidth = (UIScreen.main.bounds.width - padding.left - padding.right - (columnCount - 1) * distance) / columnCount
            
            let layout = HorizontalLayout(horizontalColumnSpace: 35.0, padding: padding, footerWidth: 0, isShowFooter: false) { () -> CGSize in
                return CGSize(width: imageWidth, height: EBookCell.cellHeight - padding.top - padding.bottom)
            }
            
            let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout).then {
                $0.isPagingEnabled = true
                $0.dataSource = self
                $0.delegate = self
                $0.showsVerticalScrollIndicator = false
                $0.showsHorizontalScrollIndicator = false
                $0.backgroundColor = UIColor.clear
                $0.decelerationRate = UIScrollView.DecelerationRate.fast
                $0.register(EBookContentCell.self, forCellWithReuseIdentifier: "EBookContentCell")
            }
            self.contentCollectionView = collectionView
            self.contentView.addSubview(collectionView)
            collectionView.snp.makeConstraints( { (make) in
                make.edges.equalToSuperview()
            })
            
        }
        
        func refresh(_ datas:[JSONObject]?) {
            self.datas = datas
            self.contentCollectionView?.reloadData()
        }
        
        required init?(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
    }
    
}

//MARK: UICollectionViewDataSource
extension HomeViewController.EBookCell : UICollectionViewDataSource {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if let datas_ = self.datas {
            return datas_.count
        } else {
            return 0
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "EBookContentCell", for: indexPath) as! EBookContentCell
        if let datas_ = self.datas , indexPath.item < datas_.count {
            cell.refresh(datas_[indexPath.item])
        }
        return cell
    }
}

//MARK: UICollectionViewDelegate
extension HomeViewController.EBookCell : UICollectionViewDelegate {
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if let datas_ = self.datas , !datas_.isEmpty, datas_.count > indexPath.item {
            self.selectedHandle?(datas_[indexPath.item])
        }
    }
}

extension HomeViewController.EBookCell {
    class EBookContentCell: UICollectionViewCell {
        
        private lazy var imageViewPhoto = UIImageView()
        private lazy var labelName = UILabel()
        private lazy var labelPrice = UILabel()
        
        override init(frame: CGRect) {
            super.init(frame: CGRect.zero)
            self.contentView.backgroundColor = UIColor.clear
            
            self.imageViewPhoto.do {
                $0.layer.shadowColor = UIColor.black.cgColor
                $0.layer.shadowOffset = CGSize(width:2.0,height:4.0)
                $0.layer.shadowOpacity = 0.3 //阴影
            }
            self.contentView.addSubview(self.imageViewPhoto)
            self.imageViewPhoto.snp.makeConstraints { (make) in
                make.left.right.top.equalToSuperview()
                make.height.equalTo(self.contentView.snp.width).multipliedBy(125.0 / 90.0)
            }
            
            self.labelName.do {
                $0.textColor = UIColor(hex: "828282")
                $0.font = UIFont.systemFont(ofSize: 12.0, weight: .light)
            }
            self.contentView.addSubview(self.labelName)
            self.labelName.snp.makeConstraints { (make) in
                make.left.right.equalToSuperview()
                make.top.equalTo(self.imageViewPhoto.snp.bottom).offset(5.0)
            }
            
            self.labelPrice.do {
                $0.textColor = UIColor(hex: "343434")
                $0.font = UIFont.systemFont(ofSize: 12.0, weight: .light)
            }
            self.contentView.addSubview(self.labelPrice)
            self.labelPrice.snp.makeConstraints { (make) in
                make.left.right.equalToSuperview()
                make.top.equalTo(self.labelName.snp.bottom).offset(5.0)
            }
            
        }
        
        func refresh(_ data:JSONObject?) {
            self.labelName.text = data?["title"] as? String
            
            // 价格
            if let price = data?["price"] as? Double {
                self.labelPrice.text = "¥\(price)"
            } else {
                self.labelPrice.text = ""
            }
            
            // 图片
            if let cover_url = data?["cover_url"] as? String,!cover_url.isEmpty,
                let baseUrl = URL(string: Router.baseUrl) {
                let imageUrl = baseUrl.appendingPathComponent(cover_url)
                self.imageViewPhoto.kf.setImage(with: imageUrl)
            } else {
                self.imageViewPhoto.image = nil
            }
            
        }
        
        required init?(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
    }
}

